package com.db.serialize.serializer;

import com.db.serialize.domain.SensorData;
import com.db.serialize.domain.SensorDataProto;
import com.google.protobuf.InvalidProtocolBufferException;

public class ProtobufSensorDataSerializer implements SensorDataSerializer {
    @Override
    public Object serialize(SensorData sensorData) {
        SensorDataProto.SensorData.Builder builder = SensorDataProto.SensorData.newBuilder();

        builder.setElevation(sensorData.getElevation());
        builder.setLatitude(sensorData.getLatitude());
        builder.setLongitude(sensorData.getLongitude());
        builder.setTemperature(sensorData.getTemperature());

        return builder.build().toByteArray();
    }

    @Override
    public SensorData deSerialize(Object data) {
        try {
            SensorDataProto.SensorData sensorDataProto = SensorDataProto.SensorData.parseFrom((byte[]) data);

            SensorData sensorData = new SensorData();
            sensorData.setElevation(sensorDataProto.getElevation());
            sensorData.setLatitude(sensorDataProto.getLatitude());
            sensorData.setLongitude(sensorDataProto.getLongitude());
            sensorData.setTemperature(sensorDataProto.getTemperature());

            return sensorData;
        } catch (InvalidProtocolBufferException e) {
            throw new RuntimeException("Invalid protocol buffer exception");
        }
    }
}
